<?php

namespace app\admin\controller;

use think\Controller;
use think\Db;
use app\admin\model\Node as NodeModel;
use think\Request;

class Mechanical extends Controller
{
   //将项目遍历到页面，显示
    public function index()
    {
        $list = db('project_application')->paginate(5);
        $page = $list->render();
        $this->assign('list', $list);
        $this->assign('page', $page);
        return view('admin@mechanical/mechanical_select',
            [
                'page'=>$page,
                'list'=>$list
            ]);
    }

    //将添加机械表单遍历到页面上。
    public function seMechanical($id,$project_name)
    {
        $id = $id;
        $project_name=$project_name;
        return view('admin@Mechanical/form',
            [
                'id'=>$id,
                'project_name'=>$project_name
            ]);
    }
    //将项目机械添加到数组库中。
    public function addMechanical(Request $request)
    {
        $data= $request->post();

        if(empty($data['project_name'])){
            $this->error('操作错误','admin/mechanical/index');
        }
        if(empty($data['project_application_id'])){
            $this->error('操作错误','admin/mechanical/index');
        }
        if(empty($data['machine_name'])){
            $this->error('请输入机械名称','admin/mechanical/index');
        }
        if(empty($data['utility_date'])){
            $this->error('请输入使用日期','admin/mechanical/index');
        }
        if(empty($data['utility_time'])){
            $this->error('请输入使用时长','admin/mechanical/index');
        }
        if(empty($data['utility_address'])){
            $this->error('请输入使用地点','admin/mechanical/index');
        }
        if(empty($data['construction_content'])){
            $this->error('请输入施工内容','admin/mechanical/index');
        }

        $appid = $data['project_application_id'];

        unset($data['project_application_id']);

        $request = db('mechanical_usage')->insertGetId($data);
        $usagedata['application_id'] = $appid;
        $usagedata['usage_id'] = $request;
        $request = db('project_usage')->insert($usagedata);
        if ($request>0){

            $this->success('机械计划添加成功',url('admin/Mechanical/index'));
        }else{
            $this->error('机械计划添加失败',url('admin/Mechanical/addMechanical'));
        }
    }
//添加机械费用
    public function selectmechanical($id)
    {
        $result = db('project_usage')->where(['application_id' => $id])->select();
        $whereplan = Array();

        foreach ($result as $v) {
            $whereplan[] = $v['usage_id'];

        }

        foreach ($whereplan as $v) {
            $data[] = db('mechanical_usage')->where('id', $v)->select();

        }

        if (empty($data)) {
            $this->success('该项目还没有机械计划', url('admin/Mechanical/index'));
        }

        return view('admin@mechanical/mechanical_index',
            ['list' => $data]
        );

    }
    //将一条数据删除
    public function delectMechanical($id)
    {
        $res = db('mechanical_usage')->where(['id'=>$id])->delete();
        $result=db('project_usage')->where('usage_id',$id)->delete();
        if ($result) {
            $info['status'] = true;
            $info['info'] ='删除成功';
        }else{
            $info['status'] = false;
            $info['info']='删除失败';
        }
        return  json($info);
    }
    //将机械费用数据库内容遍历到页面
    public function materialpall()
    {
        $list = db('mechanical_cost')->order('id desc')->paginate(7);
        $page = $list->render();
        $this->assign('list', $list);
        $this->assign('page', $page);
        return view('admin@mechanical/materialpall_select',
            [
                'page'=>$page,
                'list'=>$list
            ]
        );
    }

    public function mechanical_details($id)
    {
        $list = db('mechanical_usage')->find($id);
//        var_dump($list);
        return view('admin@mechanical/mechanical_details',
            ['list'=>$list]
        );
    }

    public function mechanical_editor($id)
    {
        $list = db('mechanical_usage')->find($id);
//        var_dump($list);
        return view('admin@mechanical/mechanical_editor',
            ['list'=>$list]
        );
    }
    //将更新机械数据
    public function  updateMechan($id)
    {
        $data=$_POST;

        $list = db('mechanical_usage')->where('id',$id)->update($data);

        if ($list) {
            $info['status'] = true;
            $info['info'] = '编辑成功';

        }else{
            $info['status'] = false;
            $info['info'] = '编辑失败';

        }
        return  json($info);
    }

   //将一条机械费用遍历到表单，可以进行更新。
    public function mechanical_cost($id)
    {
        $list = db('mechanical_cost')->find($id);
//        var_dump($list);
        return view('admin@mechanical/mechanical_cost',
            ['list'=>$list]
        );
    }
    //将更改过的数据存到数据库
    public function  updateCost($id)
    {
        $data=$_POST;
        $data['total_price'] =($data['freight'])+($data['maintenance_cost'])+($data['oil_cost'])+($data['machine_usage_cost']);
        $list = db('mechanical_cost')->where('id',$id)->update($data);
        if ($list) {
            $info['status'] = true;
            $info['info'] = '编辑成功';
        }else{
            $info['status'] = false;
            $info['info'] = '编辑失败';
        }
        return  json($info);
    }

    //查看机械费用的详情
    public  function details_cost($id)
    {
        $list = db('mechanical_cost')->where('id',$id)->find();
        return view('admin@mechanical/details_cost',
            ['list'=>$list]
        );

    }
    public function costIndex()
    {
        $list = db('mechanical_usage')->select();
        return view('admin@mechanical/form_cost',
            [
                'list'=>$list
            ]);
    }
    //添加机械费用数据
    public function insertCost()
    {
        $data = $_POST;
//        var_dump($data);exit;
        $list= db('mechanical_cost')->insert($data);
        if ($list>0){
            $this->success('机械费用添加成功','admin/mechanical/materialPall');
        }else{
            $this->error('机械费用添加失败','admin@mechanical/insertCost');
        }

    }
    //删除一条机械费用数据
    public function delectCost($id)
    {
        $result = db('mechanical_cost')->where(['id'=>$id])->delete();

        if ($result) {
            $info['status'] = true;
        }else{
            $info['status'] = false;
        }
        return  json($info);
    }

  //将数据导出execl表格
    public function getExccel()
    {
        $data=  db('mechanical_cost')->select();

                $xlsName  = "export";
                $xlsCell  = array(
                    array('id','自增ID'),
                    array('project_name','项目名字'),
                    array('machine_name','机械名称'),
                    array('freight','运费'),
                    array('maintenance_cost','维修费'),
                    array('oil_cost','油费'),
                    array('machine_usage_cost','机械使用费'),
                    array('total_price','总计'),
                );
                $this->exportExcel($xlsName,$xlsCell,$data);

    }
    public function forExccel()
    {

        return view('admin@mechanical/forExccel');
    }
//将数据导出execl表格

    public function  addExccel(Request $request)
    {
        $file = $request->file('excel');

      if(empty($file)){
          $this->error('请上传你要导入的文件','/admin/Mechanical/forExccel');
      }

        if(request() -> isPost()){

            vendor("PHPExcel.PHPExcel");

        }
        //方法一

        $objPHPExcel =new \PHPExcel();
        //获取表单上传文件
       $file = request()->file('excel');
//        var_dump($file);exit;

       $info = $file->validate(['ext' => 'xlsx,xls'])->move(ROOT_PATH . 'public');

//        var_dump($info);exit;
       //上传验证后缀名,以及上传之后移动的地址  E:\wamp\www\bick\public
          if($info)
          {
//           echo $info->getFilename();

          $exclePath = $info->getSaveName();
          //获取文件名
          $file_name = ROOT_PATH . 'public' . DS . $exclePath;
            var_dump($file_name);
          //上传文件的地址
              $objReader =\PHPExcel_IOFactory::createReader( 'Excel5');
              $obj_PHPExcel =$objReader->load($file_name, $encode = 'utf-8');
          //加载文件内容,编码utf-8
           $excel_array=$obj_PHPExcel->getSheet(0)->toArray();

           //转换为数组格式
           array_shift($excel_array);

           //删除第一个数组(标题);
           $city = [];

           $i=0;
           foreach($excel_array as $k=>$v) {
//               $city[$k]['id'] = $v[0];
               $city[$k]['project_name'] = $v[1];
               $city[$k]['machine_name'] = $v[2];
               $city[$k]['freight'] = $v[3];
               $city[$k]['maintenance_cost'] = $v[4];
               $city[$k]['oil_cost'] = $v[5];
               $city[$k]['machine_usage_cost'] = $v[6];
               $city[$k]['total_price'] = $v[7];
               $i++;

           }
              unset($city['0']);
//           var_dump($city);exit;
              $res =db("mechanical_cost")->insertAll($city);
//                var_dump($res);
             }else{

              echo $file->getError();

           }

         return $this->fetch("admin@mechanical/forExccel");


    }

       function exportExcel($expTitle,$expCellName,$expTableData){
        //include_once EXTEND_PATH.'PHPExcel/PHPExcel.php';//方法二
        $xlsTitle = iconv('utf-8', 'gb2312', $expTitle);//文件名称
        $fileName = $expTitle.date('_YmdHis');//or $xlsTitle 文件名称可根据自己情况设定
        $cellNum = count($expCellName);
        $dataNum = count($expTableData);

//        $objPHPExcel = new PHPExcel();//方法一

        $objPHPExcel = new \PHPExcel();//方法二
        $cellName = array('A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z','AA','AB','AC','AD','AE','AF','AG','AH','AI','AJ','AK','AL','AM','AN','AO','AP','AQ','AR','AS','AT','AU','AV','AW','AX','AY','AZ');
        $objPHPExcel->getActiveSheet(0)->mergeCells('A1:'.$cellName[$cellNum-1].'1');//合并单元格
        $objPHPExcel->setActiveSheetIndex(0)->setCellValue('A1', $expTitle.'  Export time:'.date('Y-m-d H:i:s'));
        for($i=0;$i<$cellNum;$i++){
            $objPHPExcel->setActiveSheetIndex(0)->setCellValue($cellName[$i].'2', $expCellName[$i][1]);
        }
        // Miscellaneous glyphs, UTF-8
        for($i=0;$i<$dataNum;$i++){
            for($j=0;$j<$cellNum;$j++){
                $objPHPExcel->getActiveSheet(0)->setCellValue($cellName[$j].($i+3), $expTableData[$i][$expCellName[$j][0]]);
            }
        }
        ob_end_clean();//这一步非常关键，用来清除缓冲区防止导出的excel乱码
        header('pragma:public');
        header('Content-type:application/vnd.ms-excel;charset=utf-8;name="'.$xlsTitle.'.xls"');
        header("Content-Disposition:attachment;filename=$fileName.xls");
        //"xls"参考下一条备注
        $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
        //"Excel2007"生成2007版本的xlsx，"Excel5"生成2003版本的xls
        $objWriter->save('php://output');
        exit;
    }

}
